//
//  AppDelegate.swift
//  MyBlog
//
//  Created by victor on 16/11/10.
//  Copyright © 2016年 victor. All rights reserved.
//

import UIKit
import UserNotifications  //iOS10推出来的
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // 应用程序额外设置
        setupBaseInfo()
        
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        
        window?.rootViewController = XTMainViewController()
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        
        return true
    }

}

// MARK: - 设置应用程序额外信息
extension AppDelegate {
    fileprivate func setupBaseInfo() {
        
        // 设置 SVProgressHUD 最小解除时间
        SVProgressHUD.showProgress(1)
        
        // 设置网络加载指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        // 设置用户授权显示通知
        // #available 是检测设备版本，如果是 10.0 以上
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge,.carPlay], completionHandler: { (success, error) in
                print("授权" + (success ? "成功" : "失败"))
            })
        } else {
            // 10.0以下
            // 取得用户授权显示通知[上方提示条/声音/badgeNumber]
            let notifySettings = UIUserNotificationSettings(types:
                [.alert,.sound,.badge], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifySettings)
        }
    }
}

//MARK: -从服务器加载程序信息
extension AppDelegate {
    fileprivate func loadAppInfo() {
        // 模拟异步
        DispatchQueue.global().async {
            // url
            let url = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            // data
            let data = NSData(contentsOfFile: url!)
            
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            
            // 直接保存在沙盒，等待下一次程序启动使用
            data?.write(toFile: jsonPath, atomically: true)
            
            print("应用程序加载完毕\(jsonPath)")
        }
    }
}



